import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Store from '../store'
import Notfound from '../views/404Notfound.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: "/",
    redirect: "/home"
  },
  {
    path: '/home',
    name: 'home',
    component: Home
  },
  {
    path: '/goods',
    name: 'Goods',
    component: () => import( /* webpackChunkName: "goods" */ '../views/Goods.vue')
  },
  {
    path: '/user',
    name: 'User',
    component: () => import(  /* webpackChunkName: "user" */ '@/views/User.vue'),
    children: [
      {
        path: 'cart',
        name: 'Cart',
        component: () => import('../components/user/Cart.vue')
      },
      {
        path: 'center',
        name: 'Center',
        component: () => import('../components/user/Center.vue')
      }
    ]
  },
  {
    path: '/order',
    name: 'Order',
    component: () => import(  /* webpackChunkName: "order" */ '@/views/Order.vue')
  },
  {
    path: '/free',
    name: 'Free',
    component: () => import(  /* webpackChunkName: "free" */ '@/views/Free.vue')
  },
  {
    path: '/details/:id',
    name: 'Details',
    component: () => import( /* webpackChunkName: "details" */ '../views/Details.vue')
  },
  {
    path:'*',
    component: Notfound
  }
]
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 导航守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/user' || to.path === '/order') {
    // 当用户想要跳转到 用户/user 页面时
    // 判断用户是否登录  -- 判断token 是否存在
    let token = localStorage.getItem('x-auth-token')
    if (token) {
      // 进行token 的鉴权 然后再去判断是否可以继续跳转
      // 我们这里只判断有没有token
      next()
    } else {
      // 给提示
      let toastObj = {
        content: "请先登录",
        icon: "danger",
      };
      Store.dispatch("AsyncToast", toastObj);
      // 打开登录框
      Store.commit('changeIsLogin', true)
    }
    return
  }
  next()
})
export default router
